import { getTagsMinDistance } from "../utils/tagsMinDistance";
export default {
  namespaced: true,
  state: {
    createTeam: {},
    teamList: [],
    teamTagsList: [],
  },
  mutations: {
    // 设置队伍列表
    setTeamList(state, list) {
      state.teamList = [...state.teamList, ...list];
    },
    // 设置标签匹配队伍列表
    setTeamTagsList(state, list) {
      state.teamTagsList = list;
    },
    // 清空残留列表数据
    clearTeamList(state) {
      state.teamList = [];
    },
    // 设置队伍详细信息
    setTeamDetail(state, value) {
      state.createTeam = value;
    },
    // 设置队伍封面(上传成功)
    setTeamCover(state, file) {
      state.createTeam.cover = file;
    },

    // 定义排序队伍列表规则
    sortTeam(state, index) {
      if (index === 1) {
        state.teamList = state.teamList.sort(
          (a, b) => b.createTime - a.createTime
        );
      }
    },
  },
  actions: {
    // 获取队伍列表
    getTeamList({ commit }, payload) {
      const db = wx.cloud.database(),
        { page, limitCount } = payload;
      return new Promise(async (resolve, reject) => {
        try {
          const res = await db
            .collection("team")
            .orderBy("createTime", "desc")
            .skip(page * limitCount)
            .limit(limitCount)
            .get();
          console.log(res.data);
          commit("setTeamList", res.data);
          // commit("sortTeam", 1);
          resolve("成功获取到队伍列表数据");
        } catch (err) {
          console.log(err);
          reject(err);
        }
      });
    },
    // 获取与用户标签匹配的队伍列表
    getTeamListByTags({ commit }, payload) {
      const db = wx.cloud.database(),
        _ = db.command,
        { tags } = payload;
      return new Promise(async (resolve, reject) => {
        try {
          const res = await db
            .collection("team")
            .orderBy("createTime", "desc")
            .get();

          // getTagsMinDistance
          const teamList = res.data;
          teamList.forEach((item) => {
            item.tagsPower = getTagsMinDistance(tags, item.tags);
          });
          teamList.sort((a, b) => a.tagsPower - b.tagsPower);
          console.log("标签获取数据：", teamList);
          commit(
            "setTeamTagsList",
            teamList.filter((item) => item.tagsPower !== tags.length)
          );
          resolve("获取成功");
        } catch (err) {
          console.log("获取用户列表失败：", err);
          reject(err);
        }
      });
    },
    // 创建队伍
    uploadTeamDetail({ state, dispatch }) {
      const db = wx.cloud.database();
      return new Promise(async (resolve, reject) => {
        try {
          const res = await db.collection("team").add({
            data: state.createTeam,
          });
          dispatch("publishTeamContent", res._id, { root: true });
          await dispatch("getUserInfo", { type: 0 }, { root: true });
          resolve(res._id);
        } catch (err) {
          console.log("创建队伍失败：", err);
          reject(err);
        }
      });
    },

    // 上传队伍封面
    uploadTeamCover({ commit }, files) {
      return new Promise(async (resolve, reject) => {
        if (!files.length) {
          resolve("无需要上传的图片");
        }
        try {
          const uploadTask = files[0],
            fileName = "teamPic/" + uploadTask.name,
            filePath = uploadTask.url;
          const res = await wx.cloud.uploadFile({
            cloudPath: fileName,
            filePath,
          });
          console.log("查看上传成功的消息：", res);
          commit("setTeamCover", res.fileID);
          resolve("封面上传成功");
        } catch (err) {
          console.log("队伍封面上传失败：", err);
          reject(err);
        }
      });
    },
    // 解散队伍
    dissolveTeam({ dispatch }, teamDetail) {
      const db = wx.cloud.database(),
        _ = db.command,
        { userList, _id, cover, _openid, author } = teamDetail;

      return new Promise(async (resolve, reject) => {
        try {
          await dispatch("disssolveTeamForAuthor", { _openid, _id }); // 移除作者的信息
          if (userList.length) {
            await dispatch("disssolveTeamForUser", { userList, _id }); // 移除已经加入队伍的用户信息
          }
          if (author.avatar !== cover) {
            // 自定义上传的封面需要进行删除
            await dispatch("deleteTeamCover", cover); // 移除队伍的封面
          }
          await db.collection("team").where({ _id }).remove(); // 删除队伍信息
          const teamTaskList = await dispatch("getTeamTaskDetail", _id); // 获取队伍任务列表的信息
          // 如果获取到，则需要同时删除任务列表
          if (teamTaskList) {
            const listId = teamTaskList._id,
              taskList = teamTaskList.tasks,
              isTeam = true;
            await dispatch(
              "m_task/deleteTaskList",
              { listId, taskList, isTeam },
              { root: true }
            );
          }
          await dispatch("getUserInfo", { type: 0 }, { root: true });
          resolve("解散队伍成功");
        } catch (err) {
          console.log("解散队伍失败：", err);
          reject(err);
        }
      });
    },

    // 移除用户加入的队伍
    disssolveTeamForUser({}, payload) {
      const db = wx.cloud.database(),
        _ = db.command,
        { userList, _id } = payload;

      return new Promise(async (resolve, reject) => {
        try {
          const tasks = userList.map((item) => {
            return db
              .collection("user")
              .where({ _openid: item })
              .update({
                data: {
                  joinTeam: _.pull(_id),
                },
              });
          });
          const res = await Promise.all(tasks);
          resolve("移除队伍成功");
        } catch (err) {
          console.log("移除队伍失败：", err);
          reject(err);
        }
      });
    },

    // 作者解散队伍
    disssolveTeamForAuthor({}, payload) {
      const db = wx.cloud.database(),
        _ = db.command,
        { _openid, _id } = payload;
      return new Promise(async (resolve, reject) => {
        try {
          const res = db
            .collection("user")
            .where({ _openid })
            .update({
              data: {
                myTeam: _.pull(_id),
              },
            });
          resolve("移除队伍成功");
        } catch (err) {
          console.log("移除队伍失败：", err);
          reject(err);
        }
      });
    },

    // 移除队伍封面文件
    deleteTeamCover({}, picFile) {
      return new Promise(async (resolve, reject) => {
        const fileList = [picFile];
        try {
          await wx.cloud.deleteFile({
            fileList,
          });
          resolve("移除队伍封面成功");
        } catch (err) {
          console.log("移除队伍封面失败：", err);
          reject(err);
        }
      });
    },

    // 获取队伍任务列表（解散队伍时同时需要删除任务列表）
    getTeamTaskDetail({}, teamId) {
      const db = wx.cloud.database();
      return new Promise(async (resolve, reject) => {
        try {
          const res = await db.collection("taskList").where({ teamId }).get();
          resolve(res.data[0]);
        } catch (err) {
          console.log("获取队伍任务列表失败：", err);
          reject(err);
        }
      });
    },

    // 踢出队伍
    kickTeamPeople({}, payload) {
      const db = wx.cloud.database(),
        _ = db.command,
        { userList, teamId } = payload;
      return new Promise(async (resolve, reject) => {
        try {
          // 移除队员用户所在的队伍id
          const tasks = userList.map(async (userId) => {
            return db
              .collection("user")
              .where({ _openid: userId })
              .update({
                data: {
                  joinTeam: _.pull(teamId),
                },
              });
          });
          await Promise.all(tasks);
          // 移除队伍中的人员列表
          await db
            .collection("team")
            .where({ _id: teamId })
            .update({
              data: {
                userList: _.pullAll(userList),
              },
            });
          resolve("踢出成功");
        } catch (err) {
          console.log("踢出失败：", err);
          reject(err);
        }
      });
    },

    // 拒绝对方加入队伍
    refuseJoinTeam({}, payload) {
      const db = wx.cloud.database(),
        _ = db.command,
        { userId, teamId } = payload;
      return new Promise(async (resolve, reject) => {
        try {
          await db
            .collection("team")
            .where({ _id: teamId })
            .update({
              data: {
                refuseList: _.push(userId),
              },
            });
          resolve("拒绝成功");
        } catch (err) {
          console.log("拒绝对方失败：", err);
          reject(err);
        }
      });
    },

    // 同意对方加入队伍
    agreeJoinTeam({}, payload) {
      const db = wx.cloud.database(),
        _ = db.command,
        { userId, teamId } = payload;
      return new Promise(async (resolve, reject) => {
        try {
          const res1 = await db
            .collection("team")
            .where({ _id: teamId })
            .update({
              data: {
                userList: _.push(userId),
              },
            });
          console.log("payload:", payload);
          console.log("加入队伍：", res1);
          const res2 = await db
            .collection("user")
            .where({ _openid: userId })
            .update({
              data: {
                joinTeam: _.push(teamId),
              },
            });
          resolve("同意加入成功！");
        } catch (err) {
          console.log("同意加入失败：", err);
          reject(err);
        }
      });
    },

    // 修改队伍信息
    changeTeamInfo({}, payload) {
      const db = wx.cloud.database(),
        { teamInfo, teamId } = payload;
      console.log("获取内容：", teamInfo, teamId);
      return new Promise(async (resolve, reject) => {
        try {
          const res = await db
            .collection("team")
            .where({ _id: teamId })
            .update({
              data: teamInfo,
            });
          resolve("修改成功");
        } catch (err) {
          console.log("修改队伍信息失败：", err);
          reject(err);
        }
      });
    },
  },
};
